﻿using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps.Core;

namespace Tequila.Phone.Controls
{
    [TemplatePart(Name = "Map", Type = typeof (Map))]
    public class PinnedMap : ContentControl
    {
        public static DependencyProperty ZoomProperty =
            DependencyProperty.Register("Zoom",
                                        typeof (double),
                                        typeof (PinnedMap),
                                        new PropertyMetadata(12.0));

        public static DependencyProperty LocationToPinProperty =
            DependencyProperty.Register("LocationToPin",
                                        typeof (GeoCoordinate),
                                        typeof (PinnedMap),
                                        null);

        public static DependencyProperty ApplicationIdProperty =
            DependencyProperty.Register("ApplicationId",
                                        typeof(string),
                                        typeof(PinnedMap),
                                        null);

        public static DependencyProperty PinLabelProperty =
            DependencyProperty.Register("PinLabel",
                                        typeof (string),
                                        typeof (PinnedMap),
                                        null);

        public PinnedMap()
        {
            DefaultStyleKey = typeof (PinnedMap);
        }

        public double Zoom
        {
            get { return (double) GetValue(ZoomProperty); }
            set { SetValue(ZoomProperty, value); }
        }

        public GeoCoordinate LocationToPin
        {
            get { return GetValue(LocationToPinProperty) as GeoCoordinate; }
            set { SetValue(LocationToPinProperty, value); }
        }

        public string ApplicationId
        {
            get { return GetValue(ApplicationIdProperty) as string; }
            set { SetValue(ApplicationIdProperty, value); }
        }

        public string PinLabel
        {
            get { return GetValue(PinLabelProperty) as string; }
            set { SetValue(PinLabelProperty, value); }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            SetMapView(GetTemplateChild("Map") as Map);
        }

        private void SetMapView(MapBase map)
        {
            if (map == null || LocationToPin == null)
            {
                return;
            }

            map.Children.Clear();

            var pushpin = new Pushpin {Location = LocationToPin, Content = PinLabel};

            map.Children.Add(pushpin);
            map.SetView(pushpin.Location, Zoom);
        }
    }
}
